package com.quan.wx.web.biz.controller.xczs;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.quan.base.common.base.web.support.controller.BaseController;
import com.quan.base.common.utils.CommonUtils;
import com.quan.base.common.utils.HttpClientUtil;
import com.quan.common.wx.utils.pay.PayNotityResult;
import com.quan.common.wx.utils.pay.PayOrderUtils;
import com.quan.common.wx.utils.pay.RefundOrderRequest;
import com.quan.common.wx.utils.pay.WXPayConfig;
import com.quan.common.wx.utils.pay.WXPayUtil;
import com.quan.xczs.rpc.api.XczsGoodsOrderService;
import com.quan.xczs.rpc.model.XczsGoodsOrder;

@RestController
@RequestMapping(value = "/wx/refund")
public class XczsRefundController extends BaseController {
	
	@Autowired
	private XczsGoodsOrderService xczsGoodsOrderService;
	
	/**
	 * 微信退款
	 * @param outTradeNo
	 * @return
	 */
	@GetMapping(value = "/toRefund/{outTradeNo}")
	public Object toRefund(@PathVariable String outTradeNo) {
		//返回客户端参数
		Map<String, Object> map = new HashMap<String, Object>() ;
		
		//根据订单编号获取订单记录
		XczsGoodsOrder order = this.xczsGoodsOrderService.getOrderByOutTradeNo(outTradeNo) ;
		
		RefundOrderRequest refundOrderRequest = new RefundOrderRequest() ;
		refundOrderRequest.setAppid(WXPayConfig.APPID);
		refundOrderRequest.setMch_id(WXPayConfig.MCH_ID);
		refundOrderRequest.setNonce_str(Sid.nextShort());
		refundOrderRequest.setOut_trade_no(order.getOutTradeNo());
		refundOrderRequest.setOut_refund_no(order.getOutTradeNo());
		refundOrderRequest.setTotal_fee(CommonUtils.moneyYuanToFen(order.getTotalFee()));
		refundOrderRequest.setRefund_fee(CommonUtils.moneyYuanToFen(order.getTotalFee()));
		refundOrderRequest.setOp_user_id(WXPayConfig.MCH_ID);
		
		refundOrderRequest.setSign(order.getSign());
		
		System.out.println(PayOrderUtils.RefundToXml(refundOrderRequest));
		
		String post = HttpClientUtil.post(WXPayConfig.REFUND_URL, PayOrderUtils.RefundToXml(refundOrderRequest), "utf-8");
		
		System.out.println(post);
		
		return map;
	}

	/**
	 * 异步接收微信支付结果通知的回调地址，通知url必须为外网可访问的url，不能携带参数
	 * 
	 * @return
	 */
	@RequestMapping(value = "/refundNotice")
	public Object paymentNotice(HttpServletRequest request) {
		Map<String,String> result = new HashMap<String,String>();
		String resultXml = null ;
		
		String payNotityResultXml = PayOrderUtils.getPayNotityResultXml(request) ;
		try {
			PayNotityResult notityResult = PayOrderUtils.getPayNotityResult(payNotityResultXml) ;
			
			boolean signatureValid = WXPayUtil.isSignatureValid(payNotityResultXml, WXPayConfig.APPKEY);
			
			//判断签名是否正确
			if(signatureValid) {
				if(null != notityResult) {
					if(notityResult.getReturn_code().equals("FAIL")) {//支付失败
						result.put("return_code", "FAIL") ;
				        result.put("return_msg", notityResult.getReturn_msg()) ;
						
					} else if(notityResult.getReturn_code().equals("SUCCESS")) { //支付成功
						//根据订单号查询数据库
						XczsGoodsOrder order = this.xczsGoodsOrderService.getOrderByOutTradeNo(notityResult.getOut_trade_no()) ;
						if(null != order) { 
							if(notityResult.getResult_code().equals("SUCCESS")) {//支付成功
								//支付状态（1：未支付，2：已支付（不确定是否支付成功），3：支付完成，4：取消支付，5：支付失败）
								
								if(order.getPayStatus() == 3) {//3:支付完成
									result.put("return_code", "SUCCESS") ;
							        result.put("return_msg", "OK") ;
							        logger.info("异步接收微信支付结果通知，该订单已记录，订单号：{}", notityResult.getOut_trade_no());
								}
								
								if(order.getPayStatus() == 1 || order.getPayStatus() == 2) {//1：未支付，2：已支付（不确定是否支付成功）
									//修改记录为支付成功
									order.setPayStatus(3);
									order.setTimeEnd(notityResult.getTime_end());
									order.setBankType(notityResult.getBank_type());
									this.xczsGoodsOrderService.updateSelective(order) ;
									
									result.put("return_code", "SUCCESS") ;
							        result.put("return_msg", "OK") ;
								}
							} else {//支付失败
								//更新数据库信息，表示该订单支付失败
								order.setPayStatus(5);//4：支付失败
								this.xczsGoodsOrderService.updateSelective(order) ;
								logger.info("异步接收微信支付结果通知，该订单支付失败，订单号：{}", notityResult.getOut_trade_no());
								
								result.put("return_code", "FAIL") ;
						        result.put("return_msg", notityResult.getReturn_msg()) ;
							}
							
						} else { //数据库中无法找到订单
							result.put("return_code", "FAIL") ;
					        result.put("return_msg", "订单不存在") ;
					        logger.info("订单不存在，订单号：{}", notityResult.getOut_trade_no());
						}
					}
				}
			} else {
				result.put("return_code", "FAIL") ;
		        result.put("return_msg", "签名错误") ;
		        logger.info("异步接收微信支付结果通知，该订单支签名失败，订单号：{}", notityResult.getOut_trade_no());
			}
			
			System.out.println("---------------------------------------------");
			System.out.println("返回状态码-----"+notityResult.getReturn_code());
			System.out.println("返回信息-----"+notityResult.getReturn_msg());
			System.out.println("业务结果-----"+notityResult.getResult_code());
			System.out.println("错误代码-----"+notityResult.getErr_code());
			System.out.println("错误代码描述-----"+notityResult.getErr_code_des());
			System.out.println("应用ID-----"+notityResult.getAppid());
			System.out.println("商户号-----"+notityResult.getMch_id());
			System.out.println("付款银行-----"+notityResult.getBank_type());
			System.out.println("现金支付金额-----"+notityResult.getCash_fee());
			System.out.println("货币种类-----"+notityResult.getFee_type());
			System.out.println("是否关注公众账号-----"+notityResult.getIs_subscribe());
			System.out.println("用户标识-----"+notityResult.getOpenid());
			System.out.println("商户订单号-----"+notityResult.getOut_trade_no());
			System.out.println("签名-----"+notityResult.getSign());
			System.out.println("总金额-----"+notityResult.getTotal_fee());
			System.out.println("交易类型-----"+notityResult.getTrade_type());
			System.out.println("信支付订单号-----"+notityResult.getTransaction_id());
			
		} catch (Exception e) {
			e.printStackTrace();
		}
        try {
        	resultXml = WXPayUtil.mapToXml(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
        //logger.info("商户处理后同步返回给微信参数：\r\n{}", resultXml);
        return resultXml;  
	}
	
}
